package com.march.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.march.entry.Employee;
import com.march.service.EmployeeService;
import com.march.common.R;
import com.march.utils.JWTUtils2;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther:
 * @create 10 -- 20:23
 */
@Slf4j
@Api(tags = "员工接口类")
@RestController
@RequestMapping("/employees")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;


    @PostMapping("/group")
    public R group(@ApiParam("员工信息") @Validated @RequestBody Employee employee){

        return employeeService.securityLogin(employee);
    }

    /**
     * 员工登录
     * @param employee
     * @param request
     * @return
     */
    @PostMapping("/clogin")
    public R cLogin(@ApiParam("员工信息") @RequestBody Employee employee, HttpServletRequest request){

        return employeeService.securityLogin(employee);
    }
    @ApiOperation("员工登录接口")
    @PostMapping("/login")
    public R<Employee> Login(@ApiParam("员工信息") @RequestBody Employee employee, HttpServletRequest request){

        //1. 将页面提交的密码进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2.查数据库，根据用户名
        String username = employee.getUsername();
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //3.如果没有查询到则返回登录失败结果
        if(emp == null){
            return R.error("登录失败");
        }
        //4.密码对比，且不正确。
        if(!emp.getPassword().equals(password)){
            return R.error("登录失败");
        }
        //5.查看员工状态，如果为已禁用状态，则返回员工已禁用的结果。
        if(emp.getStatus() == 0){
            return R.error("员工已禁用");
        }
        //6.登录成功，将员工的id存入Session并返回登录成功的结果。
        request.getSession().setAttribute("employee", emp.getId());

        //返回Token值
        Map<String,String> payload = new HashMap<>();
        payload.put("employee",emp.getUsername());
//        String token = JWTUtils.getToken(payload);
        String token = JWTUtils2.createToken(payload);

        R<Employee> success = R.success(emp);
        return success.add("token",token);
//        return R.success(emp);
    }
//    @PostMapping("/reg")
//    public R<String> reg(@RequestBody Employee employee){
//
//
//        return R.success("注册成功");
//    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
//        request.getAttribute().r;
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    @PostMapping
    public R<String> save(@RequestBody Employee employee,HttpServletRequest request){
        log.info("新增员工信息为：{}",employee.toString());
//        1.设置初始密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//
//        Long empId = (Long)request.getSession().getAttribute("employee");
//
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);

        employeeService.save(employee);
        return R.success("新增员工成功");
    }

    @GetMapping("/{id}")
    @ApiOperation("查询员工")
    public R<Employee> getEmployeeById(@ApiParam("员工ID") @PathVariable Integer id){
        log.info("查询员工id为：{}",id);
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getId, id);
        Employee emp = employeeService.getOne(lqw);
        return R.success(emp);
    }
    /*
    分页
    * */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("{},{},{}",page,pageSize,name);
//        构造分页构造器
        Page pageInfo = new Page(page,pageSize);

        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        //添加过滤条件
        lqw.like(StringUtils.isNotEmpty(name),Employee::getName,name);

        employeeService.page(pageInfo,lqw);

        return R.success(pageInfo);
    }
    /*
    更新状态
    * */
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){

        Long empId = (Long) request.getSession().getAttribute("employee");

        employee.setUpdateUser(empId);
        employee.setUpdateTime(LocalDateTime.now());

        employeeService.updateById(employee);
        return R.success("更新成功");
    }

    /*
    *
    *
    * */
}
